<?php

class Menu_items extends CActiveRecord
{
//	public $submenu = '';
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{menu_items}}';
	}

	public function rules()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$required = 'parent,active';
		foreach ($languages as $lang)
		{
			$required .= ',title_'.$lang;
		}
//		$required = rtrim($required, ',');
		
		$length = '';
		foreach ($languages as $lang)
		{
			$length .= 'title_'.$lang.',';
		}
		$length = rtrim($length, ',');
		
		$search = 'id, parent, sorter, active';
		foreach ($languages as $lang)
		{
			$search .= ', title_'.$lang;
		}
		
		return array(
			array($required, 'required'),
			array('parent, sorter, active', 'numerical', 'integerOnly'=>true),
			array($length, 'length', 'max'=>32),
			array('route', 'length', 'max'=>255),
			array($search, 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
			'order' => array(self::BELONGS_TO, 'Menu', 'id')
		);
	}

	public function attributeLabels()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$labels = array(
			'id' => 'ID',
			'route' => tt('URL'),
			'parent' => tt('Parent'),
			'sorter' => tt('Sorter'),
			'active' => tt('Active'),
		);
		foreach($languages as $lang)
		{
			$labels['title_'.$lang] = tt('Title');
		}
		
		return $labels;
	}

	public function search($menu_id, $parent = 0)
	{
		$criteria=new CDbCriteria;

		$languages = Languages::model()->getLanguageCodes();
		foreach ($languages as $lang)
		{
			$criteria->compare('title_'.$lang,$this->{'title_'.$lang},true);
		}
		$criteria->compare('route',$this->route,true);
		$criteria->compare('parent',$parent);
		$criteria->compare('menu_id',$menu_id);
		$criteria->order = 'sorter ASC';

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public function beforeSave()
	{
		if($this->isNewRecord)
		{
			$maxSorter = Yii::app()->db->createCommand()
				->select('MAX(sorter) as maxSorter')
				->from($this->tableName())
				->where('menu_id = '.$this->menu_id)
				->queryRow();
			$this->sorter = $maxSorter['maxSorter']+1;
		}
		
		return parent::beforeSave();
	}

	public function afterSave()
	{
		$menu = Menu::model()->findByPk($this->menu_id);
		Menu::updateCache($menu->label);
		parent::afterSave();
	}
	
	public function afterDelete()
	{
		$menu = Menu::model()->findByPk($this->menu_id);
		Menu::updateCache($menu->label);
		return parent::afterDelete();
	}
	
}